package com.ihemou.auth.controller;

import com.ihemou.auth.form.LoginBody;
import com.ihemou.auth.service.SysLoginService;
import com.ihemou.common.core.constant.HttpStatus;
import com.ihemou.common.core.domain.R;
import com.ihemou.common.core.utils.StringUtils;
import com.ihemou.common.security.service.TokenService;
import com.ihemou.system.dto.UserInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * token 控制
 *
 * @author ruoyi
 */
@RestController
@RequestMapping("/auth")
public class TokenController {
    @Autowired
    private TokenService tokenService;

    @Autowired
    private SysLoginService sysLoginService;

    @PostMapping("login")
    public R<?> login(@RequestBody LoginBody form) {
        if (StringUtils.isNotEmpty(form.getUsername()) && StringUtils.isNotEmpty(form.getPassword())) {
            // 用户登录
            UserInfo userInfo = sysLoginService.login(form.getUsername(), form.getPassword());
            userInfo.getSysUser().setPassword("");
            // 获取登录token
            return R.ok(tokenService.createToken(userInfo));
        } else {
            // 微信用户登录
            UserInfo userInfo = sysLoginService.weixinLogin(form);
            if(userInfo==null){
                // 自动登录失败
                return R.fail(HttpStatus.UNAUTHORIZED,"未注册");
            }
            userInfo.getSysUser().setPassword("");
            return R.ok(tokenService.createToken(userInfo));
        }
    }

    @DeleteMapping("logout")
    public R<?> logout(HttpServletRequest request) {
        UserInfo userInfo = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(userInfo)) {
            String username = userInfo.getUsername();
            // 删除用户缓存记录
            tokenService.delLoginUser(userInfo.getToken());
            // 记录用户退出日志
            sysLoginService.logout(username);
        }
        return R.ok();
    }

    @PostMapping("refresh")
    public R<?> refresh(HttpServletRequest request) {
        UserInfo userInfo = tokenService.getLoginUser(request);
        if (StringUtils.isNotNull(userInfo)) {
            // 刷新令牌有效期
            tokenService.refreshToken(userInfo);
            return R.ok();
        }
        return R.ok();
    }
}
